package com.macro.mall.service.impl;

import com.macro.mall.dao.StoreCarouselMapper;
import com.macro.mall.model.StoreCarousel;
import com.macro.mall.service.StoreCarouselService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 门店轮播图管理Service实现类
 * Created on 2025-09-16
 */
@Service
@Slf4j
public class StoreCarouselServiceImpl implements StoreCarouselService {
    
    /**
     * 轮播图最大数量限制
     */
    private static final int MAX_CAROUSEL_COUNT = 5;
    
    @Autowired
    private StoreCarouselMapper storeCarouselMapper;
    
    @Override
    public List<StoreCarousel> list() {
        log.info("获取轮播图列表");
        return storeCarouselMapper.selectList();
    }
    
    @Override
    public StoreCarousel getById(Long id) {
        if (id == null) {
            log.error("轮播图ID不能为空");
            return null;
        }
        log.info("根据ID获取轮播图信息: id={}", id);
        return storeCarouselMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public int create(String imageUrl) {
        if (!StringUtils.hasText(imageUrl)) {
            log.error("图片URL不能为空");
            throw new IllegalArgumentException("图片URL不能为空");
        }
        
        // 验证是否超过数量限制
        if (!canAddCarousel()) {
            log.error("轮播图数量已达到上限{}张", MAX_CAROUSEL_COUNT);
            throw new IllegalStateException("轮播图数量已达到上限，最多支持" + MAX_CAROUSEL_COUNT + "张图片");
        }
        
        // 简单的URL格式验证
        if (!isValidImageUrl(imageUrl)) {
            log.error("无效的图片URL格式: {}", imageUrl);
            throw new IllegalArgumentException("无效的图片URL格式");
        }
        
        // 后端额外验证：检查图片URL是否可访问（可选）
        log.info("准备添加轮播图，已通过所有验证: imageUrl={}", imageUrl);
        
        StoreCarousel carousel = new StoreCarousel();
        carousel.setImageUrl(imageUrl);
        
        int result = storeCarouselMapper.insert(carousel);
        if (result > 0) {
            log.info("成功添加轮播图: imageUrl={}, id={}", imageUrl, carousel.getId());
        } else {
            log.error("添加轮播图失败: imageUrl={}", imageUrl);
        }
        return result;
    }
    
    @Override
    @Transactional
    public int delete(Long id) {
        if (id == null) {
            log.error("轮播图ID不能为空");
            throw new IllegalArgumentException("轮播图ID不能为空");
        }
        
        // 验证轮播图是否存在
        StoreCarousel carousel = storeCarouselMapper.selectById(id);
        if (carousel == null) {
            log.error("轮播图不存在: id={}", id);
            throw new IllegalArgumentException("轮播图不存在");
        }
        
        int result = storeCarouselMapper.deleteById(id);
        if (result > 0) {
            log.info("成功删除轮播图: id={}, imageUrl={}", id, carousel.getImageUrl());
        } else {
            log.error("删除轮播图失败: id={}", id);
        }
        return result;
    }
    
    @Override
    public int getTotalCount() {
        int count = storeCarouselMapper.countTotal();
        log.info("当前轮播图总数量: {}", count);
        return count;
    }
    
    @Override
    public boolean canAddCarousel() {
        int currentCount = getTotalCount();
        boolean canAdd = currentCount < MAX_CAROUSEL_COUNT;
        log.info("验证是否可以添加轮播图: 当前数量={}, 最大限制={}, 可添加={}", 
                currentCount, MAX_CAROUSEL_COUNT, canAdd);
        return canAdd;
    }
    
    /**
     * 验证图片URL格式
     * @param imageUrl 图片URL
     * @return 是否有效
     */
    private boolean isValidImageUrl(String imageUrl) {
        if (!StringUtils.hasText(imageUrl)) {
            return false;
        }
        
        // 基础URL格式验证
        if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
            return false;
        }
        
        // 验证是否包含图片扩展名
        String lowerUrl = imageUrl.toLowerCase();
        return lowerUrl.contains(".jpg") || lowerUrl.contains(".jpeg") || 
               lowerUrl.contains(".png") || lowerUrl.contains(".gif") ||
               lowerUrl.contains(".webp") || lowerUrl.contains(".bmp");
    }
}
